package com.tanhua.server.controller;


import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.server.service.LoadService;
import com.tanhua.server.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("system/users/")
@Slf4j
public class LoadController {

    @Autowired
    private LoadService loadService;

    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public ResponseEntity<Void> layout(@RequestHeader("Authorization")String token) {

        return loadService.layout(token);

    }

    /**
     * 填充用户信息
     *
     * @param token
     * @return
     */
    @PostMapping("profile")
    public AdminVo profie(@RequestHeader("Authorization") String token) {
        AdminVo adminVo = loadService.fillAdmin(token);
        return adminVo;

    }

    /**
     * 用户输入用户名和密码登录
     *
     * @param param
     * @return
     */
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity<Object> load(@RequestBody Map<String, String> param) {
        //获得传上来的参数，先判断验证码是否正确
        String username = param.get("username");
        String password = param.get("password");
        String verificationCode = param.get("verificationCode");
        String uuid = param.get("uuid");
        String load = loadService.load(username, password, verificationCode, uuid);
        //如果返回值不是null并且不为空
        if (load != null && !load.isEmpty()) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token", load);
            return ResponseEntity.ok(map);
        }
        //以上出错，返回一个错误的响应码
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 获取验证码
     *
     * @param uuid
     * @param response
     */
    @GetMapping("verification")
    @NoAuthorization
    public void getVerificationCode(@RequestParam("uuid") String uuid, HttpServletResponse response) {
        try {
            loadService.getVerificationCode(uuid, response);
        } catch (IOException e) {
            log.error("图片验证码获取失败");
            e.printStackTrace();
        }
    }
}
